package com.xdja.study.mysql;

import com.alibaba.fastjson.JSON;
import com.xdja.study.AppConfiguration;
import com.xdja.study.mysql.bean.UserBean;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.web.RoutingContext;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserHandler {
    @Autowired
    AppConfiguration configuration;

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    public void getUser(RoutingContext routingContext) {
        //1.获取请求参数
        String userId = routingContext.request().getParam("userId");
        UserBean userBean = new UserBean();
        userBean.setUserId(userId);
        //2.从redis中获取用户名称
        this.setUser(routingContext, userBean);
        //返回结果
        logger.debug("部署完成");

    }

    private void setUser(RoutingContext routingContext, UserBean userBean) {
//        String host = configuration.redisHost();
//        int port  = configuration.redisPort();
//        final RedisClient redisClient = RedisClient.create(routingContext.vertx(),
//                new RedisOptions().setHost(host).setPort(port));
//        redisClient.get("vertx:name:" + userBean.getUserId(), data -> {
//            if(data.succeeded()) {
//                userBean.setName(data.result());
//                this.setUserFromDB(routingContext, userBean);
//            } else {
//                logger.error("从redis中获取用户信息失败:" + data.cause());
//                throw new RuntimeException(data.cause());
//            }
//        });

        this.setUserFromDB(routingContext, userBean);
    }

    private void setUserFromDB(RoutingContext routingContext, UserBean userBean) {
        final JDBCClient jdbcClient = JDBCClient.createShared(routingContext.vertx(), new JsonObject()
                .put("url", "jdbc:mysql://192.168.7.221:3306/dev_update")
                .put("driver_class", "com.mysql.jdbc.Driver")
                .put("max_pool_size", 30)
                .put("user", "update")
                .put("password", "manager"));

        jdbcClient.getConnection(conn -> {
            if(conn.failed()) {
                logger.error("从数据库获取用户信息失败：{}",  conn.cause().getMessage());
                throw new RuntimeException(conn.cause());
            }
            final SQLConnection connection = conn.result();
            connection.query("select c_id, c_password, c_name from t_update_user where c_id=" + userBean.getUserId(), rs -> {
                if(rs.result().getNumRows() > 0) {
                    String pwd = rs.result().getResults().get(0).getString(1);
                    userBean.setPwd(pwd);
                }
                int i = 0;
                connection.close(done -> {
                    if (done.failed()) {
                        throw new RuntimeException(done.cause());
                    } else {
                        this.returnResponse(routingContext, userBean);
                    }
                });
            });

        });
    }

    private void returnResponse(RoutingContext routingContext, UserBean userBean) {
        HttpServerResponse response = routingContext.response();
        response.putHeader("content-type", "application/json;charset=UTF-8").end(JSON.toJSONString(userBean));
    }


}
